package tom.spring.cloud.consumer.filter;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 自定义过滤器初始化生成requestCache上下文。<br>
 *     SpringBoot中使用Filter采用注解方式有两种。
 *      1. 注解组合WebFilter+Component+ServletComponentScan(扫描Filter组件，只在内置server时有效)
 *      2. 直接在Filter类上加Component注解即可
 *
 * @author ZHUFEIFEI
 */
@Slf4j
@Order(1)
@WebFilter(urlPatterns = "/*")
@Component
public class HystrixRequestContextInitFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //初始化requestCache上下文
        HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
        try {
            chain.doFilter(request, response);
        } catch (IOException e) {
            log.error("", e);
        } catch (ServletException e) {
            log.error("", e);
        } finally {
            ctx.shutdown();
        }
    }
}
